<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Serial Port Communication</title>
</head>
<body>
    <button onclick="connectSerial()">Connect to Serial Port</button>
    <textarea id="serialData" rows="10" cols="40" readonly></textarea>
    <video id="videoPlayer" width="640" height="360" controls></video>

    <script>
        let videoPlayer = document.getElementById('videoPlayer');
        const videoSources = [
            '1.mp4', '2.mp4', '3.mp4', '4.mp4', '5.mp4',
            '6.mp4', '7.mp4', '8.mp4', '9.mp4', '10.mp4',
            '11.mp4', '12.mp4', '13.mp4', '14.mp4', '15.mp4', '16.mp4'
        ];

        async function connectSerial() {
            try {
                const port = await navigator.serial.requestPort();
                await port.open({ baudRate: 9600 });

                const reader = port.readable.getReader();
                while (true) {
                    const { value, done } = await reader.read();
                    if (done) break;

                    const receivedData = new TextDecoder().decode(value).trim();
                    document.getElementById('serialData').value += receivedData + '\n';

                    if (receivedData === '1') {
                        playRandomVideo();
                    }
                }
            } catch (error) {
                console.error('Error connecting to serial port:', error);
            }
        }

        function playRandomVideo() {
            if (!videoPlayer.paused) {
                // 如果当前视频正在播放，则忽略新请求
                return;
            }

            // 随机选择一个视频源
            const randomIndex = Math.floor(Math.random() * videoSources.length);
            const selectedVideo = videoSources[randomIndex];

            // 设置视频源并播放
            videoPlayer.src = selectedVideo;
            videoPlayer.play();

            // 添加事件监听器以在视频结束时停止
            videoPlayer.onended = () => {
                videoPlayer.src = ''; // 清空视频源
                console.log('Video playback finished, waiting for the next signal.');
            };
        }
    </script>
</body>
</html>
